<template>
  <div>
    <el-upload
      ref="upload"
      class="avatar-uploader"
      :action="action"
      :show-file-list="false"
      :headers="headers"
      :on-success="handleSuccess"
    >
      <img v-if="imageUrl" :src="imageUrl" class="attach">
      <i v-else class="el-icon-plus attach-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import store from '@/store'
export default {
  name: 'SingleFileUpload',
  props: {
    attachFile: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      action: process.env.VUE_APP_BLOB_UPLOAD,
      headers: {},
      imageUrl: ''
    }
  },
  watch: {
    attachFile(newVal, oldVal) {
      this.imageUrl = null
      if (newVal.blobName) {
        this.imageUrl = process.env.VUE_APP_BLOB_RESOURCE + newVal.blobName
      }
    }
  },
  created() {
    if (store.getters.token) {
      this.headers['authorization'] = 'Bearer ' + store.getters.token
    }
    if (store.getters.tenant) {
      this.headers['__tenant'] = store.getters.tenant
    }
  },
  methods: {
    handleSuccess(response, file, fileList) {
      this.imageUrl = URL.createObjectURL(file.raw)

      this.attachFile.fileName = response.fileName
      this.attachFile.blobName = response.blobName
      this.attachFile.blobContainerName = response.blobContainerName
    }
  }
}
</script>
<style scoped>
.attach-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.attach-uploader-icon:hover {
  border-color: #409EFF;
}
.attach {
  width: 148px;
  height: 148px;
  display: block;
  /*border-color: #409EFF;*/
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

</style>
